package com.lbb.springboot.util;

import java.io.*;

public class FileUtils {
    /**
     * 从{@link InputStream}读取字节数组<br>
     * 结束时会关闭{@link InputStream}<br>
     * {@code in}为{@code null}时抛出{@link NullPointerException}
     *
     * @param fileName
     * @return 字节数组
     * @throws IOException
     */
    public static final byte[] readImageFile(String fileName) throws IOException {

        // 第1步、使用File类找到一个文件
        File f = new File(fileName);    // 声明File对象
        InputStream in = null;    // 准备好一个输入的对象
        in = new FileInputStream(f);    // 通过对象多态性，进行实例化

        if (null == in)
            throw new NullPointerException("the argument 'in' must not be null");
        try {
            int buffSize = Math.max(in.available(), 1024 * 8);
            byte[] temp = new byte[buffSize];
            ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);
            int size = 0;
            while ((size = in.read(temp)) != -1) {
                out.write(temp, 0, size);
            }
            return out.toByteArray();
        } finally {
            in.close();
        }
    }


    public static final byte[] input2byte(InputStream inStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }
}
